import 'dart:async';
import 'package:alipay_kit/alipay_kit.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:laos_mall/pages/order/view.dart';
import 'package:wechat_kit/wechat_kit.dart';

import '../config/app_const.dart';

class PayUtil{
  static final PayUtil _storage = PayUtil._internal();

  var payState = 0.obs;
  PayUtil._internal(){
    // _wxSubs;
    _wxSubs = WechatKitPlatform.instance.respStream().listen(_listenResp);
    _paySubs = AlipayKitPlatform.instance.payResp().listen(_listenPay);
  }
  factory PayUtil() => _storage;
  late final StreamSubscription<AlipayResp> _paySubs;
  late final StreamSubscription<WechatResp> _wxSubs;

  defaultPay(bool isAli,dynamic orderInfo){
    payState.value = 0;
    if (isAli) {
      aliPay(orderInfo);
    } else {
      wxPay(orderInfo);
    }
  }
  defaultPayFunc(bool isAli,Future<String> Function() func) async{
     var orderInfo = await func();
     defaultPay(isAli, orderInfo);
  }

  wxPay(orderInfo)async{
    await WechatKitPlatform.instance.registerApp(appId: AppConst.wxAppId, universalLink: "https://help.wechat.com/app/");
    Map<String, dynamic> param = {};
    if(orderInfo is String){
      // if(orderInfo.contains("toapp.aiyle.top")){
      //   var array = orderInfo.split("toapp.aiyle.top?");
      //   orderInfo = array.last;
      // }
      var uri = Uri.tryParse(orderInfo);
      param = uri?.queryParameters ?? {};
      print(
          "appid = ${param["appid"]}  partnerId = ${param["partnerid"]}  prepayId = ${param["prepayid"]} package = ${param["package"]}  nonceStr= ${param["noncestr"]} timeStamp = ${param["timestamp"]} sign = ${param["sign"]}");
      WechatKitPlatform.instance.pay(appId: param["appid"] ?? "",
          partnerId: param["partnerid"]!,
          prepayId: param["prepayid"]!,
          package: param["package"]!,
          nonceStr: param["noncestr"]!,
          timeStamp: param["timestamp"]!,
          sign: param["sign"]!);
    }else if(orderInfo is Map<String,dynamic>){
      param = orderInfo;
      WechatKitPlatform.instance.pay(appId: param["appId"] ?? "",
          partnerId: param["partnerId"]!,
          prepayId: param["prepayId"]!,
          package: param["packageValue"]!,
          nonceStr: param["nonceStr"]!,
          timeStamp: param["timeStamp"]!,
          sign: param["sign"]!);
    }
  }

  aliPay(String orderInfo)async{
    // var isInstalled =  await AlipayKitPlatform.instance.isInstalled();
    // if(isInstalled){
    //   SmartDialog.showToast("支付宝未安装");
    //   return;
    // }
    var newOrderInfo = orderInfo;
    if(orderInfo.contains("https://alipayh5toapp.aiyle")){
      var array = orderInfo.split("toapp.aiyle.top?");
      newOrderInfo = array.last;
    }
    AlipayKitPlatform.instance.pay(orderInfo: newOrderInfo);
  }

  void _listenResp(WechatResp resp) {
    final String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
    print(content);
    if(resp.isSuccessful){
      _callBackHandle();
    }
    // SmartDialog.showToast(content);
  }

  void _callBackHandle(){
    final logic = Get.find<OrderPage>();


    try {
      // final logic3 = Get.find<OrderDetailLogic>();
      // logic3.requestData();
      //
      // final logic1 = Get.find<BaseOrderLogic>(tag: 0.toString());
      // logic1.onRefresh();
      //
      // final logic2 = Get.find<BaseOrderLogic>(tag: 1.toString());
      // logic2.onRefresh();

    }catch(e){
      print(e.toString());
    }
  }

  void _listenPay(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    /// 9000——订单支付成功         下面的result有值
    /// 8000——正在处理中
    /// 4000——订单支付失败
    /// 5000——重复请求
    /// 6001——用户中途取消
    /// 6002——网络连接出错
    switch(resp.resultStatus){
      case 9000:
        SmartDialog.showToast("支付成功");
        payState.value = 1;
        _callBackHandle();
        break;
      case 8000:
        SmartDialog.showToast("正在处理中");
        break;
      case 4000:
        SmartDialog.showToast("订单支付失败");
        break;
      // case 5000:
      //   SmartDialog.showToast("重复请求");
      //   break;
      case 6002:
        SmartDialog.showToast("网络连接出错");
        break;
    }
  }

  static wxShare(){
  }
}